//
//  QrCodeScanAnimationView.swift
//  YYDSDemo
//
//  Created by linjw on 2020/3/10.
//
// @author Linjw(10126121@qq.com)
//

import UIKit
#if canImport(SnapKit)
import SnapKit
#endif

/// 扫描线动画类型
@objc public enum JWQRCodeScanLineAnimationStyle: Int {
    /// 单向(自上而下，循环)
    case oneWay
    /// 循环(自上而下再上，循环)
    case loop
}

/// 扫描视图
@objcMembers public class JWQRCodeScanAnimationView: UIView {
    
    /// 动画类型
    public lazy var animationType: JWQRCodeScanLineAnimationStyle = .loop
    
    /// 是否正在进行动画
    public var isAnimation: Bool { return isAnimating }
    
    /// 是否正在进行动画
    private(set) lazy var isAnimating: Bool = false
    
    /// 扫描框
    public lazy var scanContainerImageView: UIImageView = {
        let it = UIImageView()
        it.translatesAutoresizingMaskIntoConstraints = false
        let moduleBundle = Bundle(for: JWQRCodeManager.self)
        if let imageBundlePath = moduleBundle.path(forResource: "JWQRCodeManager", ofType: "bundle"),
           let imageBundle = Bundle(path: imageBundlePath),
           let imagePath = imageBundle.path(forResource: "JWQRCodeManager.bundle/ChooseScanningFrame", ofType: "png") {
            it.image = UIImage(contentsOfFile: imagePath)
        }
        return it
    }()
    
    /// 背景网图
    public lazy var backgroundImageView: UIImageView = {
        let it = UIImageView()
        it.translatesAutoresizingMaskIntoConstraints = false
        it.setContentCompressionResistancePriority(.defaultHigh + 5, for: .horizontal)
        let moduleBundle = Bundle(for: JWQRCodeManager.self)
        if let imageBundlePath = moduleBundle.path(forResource: "JWQRCodeManager", ofType: "bundle"),
           let imageBundle = Bundle(path: imageBundlePath),
           let imagePath = imageBundle.path(forResource: "JWQRCodeManager.bundle/ChooseScanningMesh", ofType: "png") {
            it.image = UIImage(contentsOfFile: imagePath)
        }
        return it
    }()
    
    /// 动画线
    public lazy var lineImageView: UIImageView = {
        let it = UIImageView()
        it.translatesAutoresizingMaskIntoConstraints = false
        it.setContentCompressionResistancePriority(.defaultHigh + 5, for: .horizontal)
        let moduleBundle = Bundle(for: JWQRCodeManager.self)
        if let imageBundlePath = moduleBundle.path(forResource: "JWQRCodeManager", ofType: "bundle"),
           let imageBundle = Bundle(path: imageBundlePath),
           let imagePath = imageBundle.path(forResource: "JWQRCodeManager.bundle/ChooseScanningLine", ofType: "png") {
            it.image = UIImage(contentsOfFile: imagePath)
        }
        return it
    }()
    
    override public init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required public init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    func setupUI() {
        
        backgroundColor = .clear

        addSubview(scanContainerImageView)
        addSubview(backgroundImageView)
        addSubview(lineImageView)
        
        NSLayoutConstraint.activate([
            scanContainerImageView.leftAnchor.constraint(equalTo: self.leftAnchor),
            scanContainerImageView.rightAnchor.constraint(equalTo: self.rightAnchor),
            scanContainerImageView.topAnchor.constraint(equalTo: self.topAnchor),
            scanContainerImageView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
        ])
        
        NSLayoutConstraint.activate([
            backgroundImageView.leftAnchor.constraint(equalTo: self.leftAnchor),
            backgroundImageView.rightAnchor.constraint(equalTo: self.rightAnchor),
            backgroundImageView.topAnchor.constraint(equalTo: self.topAnchor),
            backgroundImageView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
        ])
        
        NSLayoutConstraint.activate([
            lineImageView.leftAnchor.constraint(equalTo: self.leftAnchor),
            lineImageView.rightAnchor.constraint(equalTo: self.rightAnchor),
            lineImageView.topAnchor.constraint(equalTo: self.topAnchor),
            lineImageView.heightAnchor.constraint(equalToConstant: 6)
        ])
    }
    
}

public extension JWQRCodeScanAnimationView {
    
    /// 开始动画
    func startAnimation() {
        
        // 动画采用CAAnimation、也可用timer和CAShapelayer
        
        // 为了能获取到位置和宽高
        layoutIfNeeded()
        
        switch animationType {
        case .oneWay:
            let animation = CABasicAnimation.init(keyPath: "transform.translation.y")
            animation.fromValue = 0
            animation.toValue = bounds.size.height - 6
            animation.timingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.easeInEaseOut)
            animation.duration = 2
            animation.isRemovedOnCompletion = false
            animation.repeatCount = MAXFLOAT
            lineImageView.layer.add(animation, forKey: "y_transaltion")
        case .loop:
            let animation = CAKeyframeAnimation(keyPath: "transform.translation.y")
            animation.values = [0, bounds.size.height - 6, 0]
            animation.timingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.linear)
            animation.duration = 3
            animation.isRemovedOnCompletion = false
            animation.repeatCount = MAXFLOAT
            lineImageView.layer.add(animation, forKey: "y_transaltion")
        }
        
        isAnimating = true // lineImageView.layer.animation(forKey: "y_transaltion")

    }
    
    /// 结束动画
    func stopAnimation() {
        lineImageView.layer.removeAnimation(forKey: "y_transaltion")
        isAnimating = false // lineImageView.layer.animation(forKey: "y_transaltion")
    }
    
}


